package api

import (
	"blog/helper"
	"encoding/json"
	"github.com/astaxie/beego"
	"math"
)

type baseController struct {
	beego.Controller
	Page  int
	Limit int
	api   *helper.Api
}

func (b *baseController) Prepare() {
	b.Limit, _ = b.GetInt("limit", 20)
	b.Page, _ = b.GetInt("page", 1)
}

func (b *baseController) NewApi() *baseController {
	b.api = helper.NewApi()
	return b
}

//@params total 总条数
func (b *baseController) Pagination(total int64) *baseController {
	var totalPage int = int(math.Ceil(float64(total) / float64(b.Limit)))
	b.api.SetPagination(b.Page, b.Limit, totalPage, int(total))
	return b
}

func (b *baseController) Success(data interface{}, message ...string) {
	b.Data["json"] = b.api.Success(data, message...)
	b.ServeJSON()
	b.StopRun()
}

func (b *baseController) Error(message string) {
	b.Data["json"] = b.api.Error(message)
	b.ServeJSON()
	b.StopRun()
}

func (b *baseController) LoadData(model interface{}) error {
	err := json.Unmarshal(b.Ctx.Input.RequestBody, model)
	return err
}
